/*
 * @Author: isaac
 * @LastEditors: isaac
 * @Description:
 * i made my own lucky
 */
import React, { createContext, useContext, useMemo } from 'react';
import { DataSet } from 'choerodon-ui/pro';
import { inject } from 'mobx-react';
import { observer } from 'mobx-react-lite';
import { get as getInject } from '@choerodon/inject';
import { BUILD_DOCKER, BUILD_MAVEN_PUBLISH, BUILD_UPLOADJAR } from '@/routes/app-pipeline/CONSTANTS';
import conGroupDataSet
  from '@/routes/app-center-pro/components/OpenAppCreateModal/components/container-config/stores/conGroupDataSet';

interface ContextType {
  cRef: any,
  children: any,
  ConGroupDataSet: any,
  modal?: any,
  detail?: any,
  refresh?: Function,
  isPipeline?: Boolean,
  preJobList?: object[],
}

const Store = createContext({} as any);

export function useContainerConfig() {
  return useContext(Store);
}

export const StoreProvider = inject('AppState')(observer((props: any) => {
  const {
    children,
    isPipeline,
    preJobList,
    AppState: { currentMenuType: { projectId } },
    disabled,
  } = props;

  let dockerData: any[] = [];
  let jarData: any[] = [];
  if (preJobList && preJobList.length > 0) {
    dockerData = preJobList
      .filter((itemList: any) => itemList?.devopsCiStepVOList
        ?.some((c: any) => c.type === BUILD_DOCKER));
    jarData = preJobList
      .filter((itemList: any) => itemList?.devopsCiStepVOList
        ?.some((c: any) => [BUILD_MAVEN_PUBLISH, BUILD_UPLOADJAR].includes(c?.type)));
  }

  const ctyunInCreatingDefaultSelect = getInject('configuration.devops-routes-application-center:createApp-inCreatingDefaultSelect');

  const ConGroupDataSet = useMemo(
    () => new DataSet(conGroupDataSet(
      isPipeline,
      preJobList,
      ctyunInCreatingDefaultSelect,
      dockerData,
      jarData,
      projectId,
      disabled,
    )), [isPipeline, preJobList, dockerData, jarData],
  );

  const value = {
    ...props,
    ConGroupDataSet,
    dockerData,
    jarData,
  };

  return (
    <Store.Provider value={value}>
      {children}
    </Store.Provider>
  );
}));
